const express = require('express')
const app = express()
const multer = require('multer')
const port = 3000 // 端口号

// 文件操作
const fs = require('fs')
const path = require('path')

// 使用multer插件，设置文件上传的路径
const upload = multer({
	dest: 'data/'
});

// 配置静态资源路径
app.use(express.static(path.join(__dirname, 'data')));

// 解决跨域
app.all('*', function(req, res, next) {
	res.header('Access-Control-Allow-Origin', '*');
	res.header('Access-Control-Allow-Headers', 'Content-Type');
	res.header('Access-Control-Allow-Methods', '*');
	res.header('Content-Type', 'application/json;charset=utf-8');
	next();
});

// 处理post图片上传上来的数据
app.post('/upload', upload.any(), function(req, res, next) {
	console.log(req.files[0]); // 上传的文件信息

	var des_file = "./data/" + req.files[0].originalname;
	// req.files[0].path即 multer设置的文件上传的路径
	fs.readFile(req.files[0].path, function(err, data) {
		fs.writeFile(des_file, data, function(err) {
			if (err) {
				console.log(err);
			} else {
				response = {
					message: 'File uploaded successfully',
					filename: req.files[0].originalname
				};
				console.log(response);
				res.send({
					data: JSON.stringify(response),
					info: "aaaa"
				});
				// 删除原来multer存的文件
				fs.unlinkSync(req.files[0].path)
			}
		});
	});
});

app.listen(port, () => console.log(`服务器启动成功，端口号为： ${port}!`))
